﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Threading;
using System.Net;
using Newtonsoft.Json;

namespace RuneLogLoader
{
    public delegate void PageLoadedEventHandler(object sender, PageLoadedEventArgs e);

    public class PageLoader
    {
        public event PageLoadedEventHandler PageLoaded;

        public bool Running
        {
            get
            {
                return loadingThread.IsAlive;
            }
        }
 
        private Thread loadingThread;
        private Dispatcher mainThread;

        private WebClient web;
        private int timeout = 3000;

        private const string CategoryBaseAdress = "http://services.runescape.com/m=itemdb_rs/api/catalogue/category.json?category=";

        private string CategoryAdress(int category)
        {
            return CategoryBaseAdress + category;
        }
        private string CatalogueAdress(int category, char alpha, int page) {
            StringBuilder sb = new StringBuilder();
            sb.Append("http://services.runescape.com/m=itemdb_rs/api/catalogue/items.json?category=");
            sb.Append(category);
            sb.Append(String.Format("&alpha=%{0:x2}", (ushort)alpha)); 
            sb.Append("&page=" + page);
            return sb.ToString();
        }

        public PageLoader()
        {
            web = new WebClient();
            mainThread = Dispatcher.CurrentDispatcher;
            loadingThread = new Thread(Run);
        }

        protected void OnPageLoaded(object sender, PageLoadedEventArgs e)
        {
            if (PageLoaded != null)
                PageLoaded(sender, e);
        }

        public void StartLoading()
        {
            if (Running)
                return;
            loadingThread.Start();
            Dispatcher.Run();
        }

        private void Run()
        {
            for (int i = 0; i < 38; i++)
            {
                var list = JsonConvert.DeserializeObject<CategoryRootObject>(DownloadString(CategoryAdress(i)));
                foreach (Alpha a in list.alpha)
                {
                    for (int j = 0; j < Math.Ceiling((double)a.items / 12.0d); j++)
                    {
                        Console.WriteLine("----");
                        var page = JsonConvert.DeserializeObject<CatalogueRootObject>(DownloadString(CatalogueAdress(i, a.letter[0], j + 1)));
                        var temp = new Dictionary<int, string>();
                        foreach (var item in page.items)
                        {
                            temp.Add(item.id, item.name);
                        }
                        OnPageLoadedThread(this, new PageLoadedEventArgs(temp));
                    }
                }
            }
        }

        private void OnPageLoadedThread(object sender, PageLoadedEventArgs e)
        {
            runOnMainThread((PageLoadedEventHandler)OnPageLoaded, sender, e);
        }

        private void runOnMainThread(Delegate d, params object[] args)
        {
            mainThread.BeginInvoke(d, args);
        }

        private string DownloadString(string adress)
        {
            Thread.Sleep(timeout);
            return web.DownloadString(adress);
        }
    }

    public class PageLoadedEventArgs : EventArgs
    {
        public Dictionary<int, string> ItemInfo
        {
            get;
            private set;
        }
        public PageLoadedEventArgs(Dictionary<int, string> infolist)
        {
            ItemInfo = infolist;
        }
    }
}
